package com.yupi.lkzyoj.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.lkzyoj.common.ErrorCode;
import com.yupi.lkzyoj.constant.CommonConstant;
import com.yupi.lkzyoj.exception.BusinessException;
import com.yupi.lkzyoj.model.dto.question.QuestionQueryRequest;
import com.yupi.lkzyoj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.yupi.lkzyoj.model.dto.questionsubmit.QuestionSubmitCurQueryRequest;
import com.yupi.lkzyoj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.yupi.lkzyoj.model.entity.Question;
import com.yupi.lkzyoj.model.entity.QuestionSubmit;
import com.yupi.lkzyoj.model.entity.QuestionSubmit;
import com.yupi.lkzyoj.model.entity.User;
import com.yupi.lkzyoj.model.enums.LanguageEnum;
import com.yupi.lkzyoj.model.enums.QuestionSubmitStatusEnum;
import com.yupi.lkzyoj.model.vo.QuestionSubmitVO;
import com.yupi.lkzyoj.model.vo.QuestionVO;
import com.yupi.lkzyoj.model.vo.UserVO;
import com.yupi.lkzyoj.service.QuestionService;
import com.yupi.lkzyoj.service.QuestionSubmitService;
import com.yupi.lkzyoj.service.QuestionSubmitService;
import com.yupi.lkzyoj.mapper.QuestionSubmitMapper;
import com.yupi.lkzyoj.service.UserService;
import com.yupi.lkzyoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Wei
 * @description 针对表【question_submit(题目提交)】的数据库操作Service实现
 * @createDate 2024-05-23 14:37:43
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public Long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionSubmitAddRequest.getQuestionId());
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        if (LanguageEnum.getEnumByValue(questionSubmitAddRequest.getLanguage()) == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言暂不支持");
        }

        // 是否已提交题目
        long userId = loginUser.getId();
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionSubmitAddRequest.getQuestionId());
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());

        questionSubmit.setLanguage(questionSubmitAddRequest.getLanguage());
        questionSubmit.setJudgeInfo("{}");
        boolean result = save(questionSubmit);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        return questionSubmit.getId();
    }

    /**
     * 获取查询包装类
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        Integer status = questionSubmitQueryRequest.getStatus();

        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        String sortField = questionSubmitQueryRequest.getSortField();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }


    /**
     * 获取问题提交vo
     *
     * @param questionSubmit 问题
     * @param request        要求
     * @return {@link QuestionSubmitVO}
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, HttpServletRequest request) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        long questionSubmitId = questionSubmit.getId();
        // 1. 关联查询用户信息
        Long userId = questionSubmit.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionSubmitVO.setUserVO(userVO);

        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, HttpServletRequest request) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionSubmitList.stream().map(QuestionSubmit::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));

        // 填充信息
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
            Long userId = questionSubmit.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionSubmitVO.setUserVO(userService.getUserVO(user));
            return questionSubmitVO;
        }).collect(Collectors.toList());

        // 权限过滤: 非本人或管理员只能查看提交信息不能查看提交的代码
        User loginUser = userService.getLoginUser(request);

        questionSubmitVOList.stream().forEach(questionSubmitVO -> {
            if (!questionSubmitVO.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                questionSubmitVO.setCode("您无权查看该用户的代码");
            }
        });

        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

    @Override
    public void deleteQuestionSubmitByQuestionId(Long id) {
        LambdaQueryWrapper<QuestionSubmit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionSubmit::getQuestionId, id);

        baseMapper.delete(wrapper);
    }

    @Override
    public List<QuestionSubmitVO> listCurQuestionSubmitByPage(QuestionSubmitCurQueryRequest questionSubmitQueryPageRequest, HttpServletRequest request) {
        //      查询提交表中所有当前用户的本题提交
        LambdaQueryWrapper<QuestionSubmit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionSubmit::getUserId, questionSubmitQueryPageRequest.getUserId());
        wrapper.eq(QuestionSubmit::getQuestionId, questionSubmitQueryPageRequest.getQuestionId());

        QuestionSubmitMapper mapper = getBaseMapper();
        List<QuestionSubmit> temp = mapper.selectList(wrapper);

        ArrayList<QuestionSubmitVO> res = new ArrayList<>();
        for (QuestionSubmit t : temp) {
            res.add(QuestionSubmitVO.objToVo(t));
        }

        return res;
    }


}



